<?php
Yii::import('lib.models.ar.adv.*');
class ActiveRecord extends CActiveRecordAdv {
	
	protected $_config = null;

	public function getConfig() {
		if(!$this->_config) {
			$this->_config = ModelConfigManager::load($this);
		}
		return $this->_config;
	}
	
	public function defaultScope() {
		return $this->config->defaultScope;
	}

	public function primaryKey() {
		if($this->config->pkName) {
			return $this->config->pkName;
		}
		return parent::primaryKey();
	}
	
	public function tableName() {
		if(!$this->config->tableName) {
			return $this->mdc->tableName();	
		}
		return $this->config->tableName;
	}
	
	public function cascade() {
		return $this->config->cascade;
	}
	
	protected function beforeValidate() {
		if(parent::beforeValidate()) {
			if(in_array('object_type', $this->attributeNames())) {
				if($this->config->object_type) {
					$this->object_type = $this->config->object_type;
				} else {
					$this->object_type = get_class($this);
				}
			}
			return true;
		} else {
			return false;
		}
	}
	
	protected function instantiate($attributes) {
		if(isset($attributes['object_type']) && $attributes['object_type']) {
			$model = new $attributes['object_type'](null);
			return $model;
		} else {
			return parent::instantiate($attributes);
		}
	}
	
	/**
	 * behavior 如果要继承使用父类的 behaviors 请使用 array_merge 方法
	 * 否则直接返回 array 数组
	 */
	public function behaviors() {
		return $this->config->behaviors;
	}
	
	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return $this->config->relations;
	}
	
	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array_merge(parent::rules(), $this->config->rules);
	}
	
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array_merge(parent::attributeLabels(), $this->config->attributeLabels);
	}
	
	public function attributeHints() {
		return $this->config->attributeHints;
	}
	
	public function getAttributeHint($attribute) {
		$hints = $this->attributeHints();
		return isset($hints[$attribute]) ? $hints[$attribute] : null;
	}
	
//	public function search() {
//		return new CActiveDataProvider($this);
//	}
	
	public function __get($name) {
		if(isset($this->config->$name)) {
			return $this->config->$name;
		}
		return parent::__get($name);
	}
}

